package com.crazymaker.demo.auth;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.crazymaker.springcloud.common.constants.SessionConstants;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.Date;

@Slf4j
public class JwtDemo {

    @Test
    public void testBaseJWT() {
        String subject = "session id";

        /**
         * 签名的加密盐
         */
        String salt = "user password";

        /**
         * 签名的加密算法
         */
        Algorithm algorithm = Algorithm.HMAC256(salt);

        long start = System.currentTimeMillis() - 60000;

        Date end = new Date(start + SessionConstants.SESSION_TIME_OUT * 1000);
        String token = JWT.create()
                .withSubject(subject)
                .withIssuedAt(new Date(start))
                .withExpiresAt(end)
                .sign(algorithm);
        // 对token进行解码
        DecodedJWT jwt = JWT.decode(token);
        log.info("jwt token = {}", jwt.getSubject());
        log.info("token = {}", token);
    }
}
